package com.lfs.adapter.service.impl;

import com.lfs.adapter.service.ChannelSupplierService;
import com.lfs.adapter.util.JsonObjectUtil;
import com.lfs.common.cache.redis.base.MapCache;
import com.lfs.common.constant.Constant;
import com.lfs.interfaces.dao.BaseChargeDao;
import com.lfs.interfaces.model.ChannelSupplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChannelSupplierServiceImpl implements ChannelSupplierService {
    @Autowired
    private MapCache mapCache;

    @Autowired
    private BaseChargeDao baseChargeDao;

    /**
     * 获取所有的通道供应商
     *
     * @return
     */
    public List<ChannelSupplier> getAllChannelSupplier() {

        return baseChargeDao.selectList("ChannelSupplierMapper.selectAllChannel_supplier");
    }

    /**
     * 更新余额
     *
     * @return
     */
    public int updateChanneSupplierBalance(String supplier_code, BigDecimal balance) {

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("supplier_code", supplier_code);
        param.put("balance", balance);
        return baseChargeDao.update("ChannelSupplierMapper.updateChannelBalance", param);
    }

    /**
     * 置为失效状态
     *
     */
    public int updateChannelSupplier(ChannelSupplier channelSupplier) {
        return baseChargeDao.update("ChannelSupplierMapper.updateChannelStatus", channelSupplier);
    }

    /**
     * 置为失效状态
     *
     * @param supplier_code
     */
    public int updateChannelSupplierValid(String supplier_code) {
        return baseChargeDao.update("ChannelSupplierMapper.updateChannelStatus", supplier_code);
    }

    /**
     * 根据channle_code获取通道信息 从redis中获取
     *
     * @return
     */
    public ChannelSupplier queryChannelConfigByCodeCache(String supplierCode) {
        // 1.从redis获取
        String result =(String)mapCache.hget(Constant.T_CHANNEL_SUPPLIER,supplierCode);
        // json序列化
        ChannelSupplier channelSupplier = JsonObjectUtil.json2object(result, ChannelSupplier.class);
        // 2.redis不存在
        if (channelSupplier == null) {
            // 从数据库获取
            channelSupplier = baseChargeDao.selectOne("ChannelSupplierMapper.selectByPrimaryKey", supplierCode);
            if (channelSupplier != null) {
                // 存入数据库
                mapCache.hset(Constant.T_CHANNEL_SUPPLIER, supplierCode, JsonObjectUtil.object2json(channelSupplier));
            }
        }
        return channelSupplier;
    }

    public List<ChannelSupplier> queryChannelConfigByAdapterName(String adapterName) {

        return baseChargeDao.selectList("ChannelSupplierMapper.selectByAdapterName", adapterName);
    }

    public Map<String, Object> getNotifyInfo(String orderNo) {
        return baseChargeDao.selectOne("ChannelSupplierMapper.getNotifyInfo",orderNo);
    }
}
